package com.znjc.web.controller.device;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysDept;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.StringUtils;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.service.IIotSerialService;
import com.znjc.device.service.TaskSchedulerService;
import com.znjc.device.websocket.WebSocketUsers;
import com.znjc.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 【串口】Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@Slf4j
@RestController
@RequestMapping("/device/serial")
public class IotSerialController extends BaseController {
    @Autowired
    private IIotSerialService iotSerialService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private TaskSchedulerService taskSchedulerService;

    /**
     * 查询串口管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:serial:list')")
    @GetMapping("/list")
    public TableDataInfo list(IotSerial iotSerial) {
        startPage();
        LambdaQueryWrapper<IotSerial> wrapper = getWrapper(iotSerial);
        List<IotSerial> list = iotSerialService.list(wrapper);
        return getDataTable(packList(list));
    }

    /**
     * 导出串口管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:serial:export')")
    @Log(title = "串口管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotSerial iotSerial) {
        LambdaQueryWrapper<IotSerial> wrapper = getWrapper(iotSerial);
        List<IotSerial> list = iotSerialService.list(wrapper);
        ExcelUtil<IotSerial> util = new ExcelUtil<IotSerial>(IotSerial.class);
        util.exportExcel(response, packList(list), "串口管理数据");
    }

    /**
     * 获取串口管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:serial:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(iotSerialService.getById(id));
    }

    /**
     * 新增串口管理
     */
    @PreAuthorize("@ss.hasPermi('device:serial:add')")
    @Log(title = "串口管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotSerial iotSerial) {
        iotSerial.setGatherType("1");
        return toAjax(iotSerialService.save(iotSerial));
    }

    /**
     * 修改串口管理
     */
    @PreAuthorize("@ss.hasPermi('device:serial:edit')")
    @Log(title = "串口管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotSerial iotSerial) {
        IotSerial oldData = iotSerialService.getById(iotSerial.getId());
        if (!oldData.getSerialCode().equals(iotSerial.getSerialCode())) {
            return error("串口号不能修改！");
        }
        //修改了采集时间
        if (null != oldData && "0".equals(oldData.getGatherType())
                && StringUtils.isNotEmpty(oldData.getGatherTime())
                && !oldData.getGatherTime().equals(iotSerial.getGatherTime())) {
            JSONObject json = new JSONObject();
            json.put("openFlag", "0");
            json.put("serial", iotSerial);
            json.put("cronFlag", true);
            WebSocketUsers.sendMessageToUserByText(iotSerial.getDeptId() + "", json.toJSONString());
        }
        //关闭串口
        if (StringUtils.isNotEmpty(oldData.getStatus()) && "0".equals(oldData.getStatus())
                && StringUtils.isNotEmpty(iotSerial.getStatus()) && "1".equals(iotSerial.getStatus())) {
            iotSerial.setDeptId(oldData.getDeptId());
            iotSerialService.closePort(iotSerial);
        }
        return toAjax(iotSerialService.updateById(iotSerial));
    }

    /**
     * 删除串口管理
     */
    @PreAuthorize("@ss.hasPermi('device:serial:remove')")
    @Log(title = "串口管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<Long> idsList = new ArrayList<>(Arrays.asList(ids));
        if (CollectionUtils.isNotEmpty(idsList)) {
            List<IotSerial> list = iotSerialService.listByIds(idsList);
            Boolean flag = iotSerialService.removeByIds(idsList);
            if (flag && CollectionUtils.isNotEmpty(list)) {
                for (IotSerial serial : list) {
                    iotSerialService.closePort(serial);
                }
            }
            return toAjax(flag);
        }
        return success();
    }

    /**
     * 查询公共方法
     *
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(IotSerial entity) {
        LambdaQueryWrapper<IotSerial> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (StringUtils.isNotEmpty(entity.getSerialCode())) {
                wrapper.like(IotSerial::getSerialCode, entity.getSerialCode());
            }
        }
        return wrapper;
    }

    /**
     * 结果封装
     *
     * @param list
     * @return
     */
    private List<IotSerial> packList(List<IotSerial> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if (null != entity.getDeptId()) {
                    SysDept dept = deptService.selectDeptById(entity.getDeptId());
                    if (null != dept) {
                        entity.setDeptName(dept.getDeptName());
                    }
                }
            });
        }
        return list;
    }

    /**
     * 开启关闭采集
     */
    @PreAuthorize("@ss.hasPermi('device:serial:cjkg')")
    @Log(title = "串口管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editGather/{id}/{status}")
    public AjaxResult editGather(@PathVariable("id") Long id, @PathVariable("status") String status) {
        IotSerial serial = iotSerialService.getById(id);
        boolean flag = true;
        if (serial != null) {
            if (!"3".equals(serial.getDeviceType())) {
                if (CollectionUtils.isEmpty(WebSocketUsers.getUsers()) || !WebSocketUsers.getUsers().keySet().contains(serial.getDeptId() + "")) {
                    return error(serial.getDeptId() + "不在线,无法下发指令。");
                }
                serial.setGatherType(status);
                try {
                    iotSerialService.editGather(serial, status);
                } catch (Exception e) {
                    return error(e.getMessage());
                }
            } else {
                //回流采集
                serial.setGatherType(status);
                iotSerialService.updateById(serial);
                if ("0".equals(status)) {
                    try {
                        // 启动采集任务
                        boolean success = taskSchedulerService.startCollectionTask(serial);

                        if (success) {
                            log.info("串口 {} 采集任务启动成功", serial.getSerialCode());
                            return AjaxResult.success("采集任务启动成功");
                        } else {
                            return AjaxResult.error("采集任务启动失败");
                        }
                    } catch (Exception e) {
                        log.error("启动串口采集时发生异常：", e);
                        return AjaxResult.error("启动串口采集时发生异常：" + e.getMessage());
                    }
                } else {
                    try {
                        boolean success = taskSchedulerService.stopCollectionTask(serial.getSerialCode());

                        if (success) {
                            log.info("串口 {} 采集任务停止成功", serial.getSerialCode());
                            return AjaxResult.success("采集任务停止成功");
                        } else {
                            return AjaxResult.error("采集任务停止失败");
                        }
                    } catch (Exception e) {
                        log.error("停止串口采集时发生异常：", e);
                        return AjaxResult.error("停止串口采集时发生异常：" + e.getMessage());
                    }
                }

            }

        }
        return toAjax(flag);
    }

    /**
     * 检查采集状态
     */
    @GetMapping("/status/{serialCode}")
    @ApiOperation("检查采集状态")
    public AjaxResult getCollectionStatus(@PathVariable String serialCode) {
        try {
            boolean isRunning = taskSchedulerService.isTaskRunning(serialCode);
            return AjaxResult.success("查询成功", isRunning ? "运行中" : "已停止");

        } catch (Exception e) {
            log.error("查询采集状态异常: {}", e.getMessage(), e);
            return AjaxResult.error("查询采集状态异常: " + e.getMessage());
        }
    }

}
